<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Api\BaseController;
use Illuminate\Support\Facades\Validator;
use App\Services\AliMsg;
use Illuminate\Support\Facades\Cache;

class BrokerController extends BaseController
{
    /**
     * 发送短信验证码
     * @return false|string
     */
    public function sendTelMsg(){
        //校验参数
        $validator = Validator::make($this->request, [
            'tel' => 'required|size:11',
        ],[
            'tel.required' => '缺少手机号',
            'tel.size' => '手机号长度为11',
        ]);
        if ($validator->fails()) {
            return $this->sendJson($validator->getMessageBag()->toArray(),'error param','400000');
        }

        $phoneNum = $this->request['tel'];

        $code = Cache::get($phoneNum);
        if (!empty($code)){
            return $this->sendJson('','您已发送，请勿重复点击','500001');
        }

        //判断该手机号今日发送短信次数
        $num=Cache::get($phoneNum.date('Y-m-d'));
        if (5 <= $num){
            return $this->sendJson('','您今日已发送5次，请明日再试或联系管理员','500001');
        }

        //发送短信验证码
//        $sendResult = AliMsg::send($phoneNum);
        $sendResult = '123456';

        //判断是否发送成功
        if ($sendResult){

            //设置120秒的验证码
            Cache::put("$phoneNum",$sendResult,120);

            //设置该手机号今日内的发送短信次数
            $num=$num+1;
            Cache::put($phoneNum.date('Y-m-d'),$num,24*3600);

            return $this->sendJson($sendResult,'手机验证码发送成功');
        }else{
            return $this->sendJson('','发送失败，请稍后重试或联系管理员','500000');
        }
    }

    /**
     * 经纪人登录
     * @return false|string
     */
    public function login(){
        //校验参数
        $validator = Validator::make($this->request, [
            'tel' => 'required|size:11',
            'code' => 'required|size:11'
        ],[
            'tel.required' => '缺少手机号',
            'tel.size' => '手机号长度为11',
            'code.required' => '缺少验证码',
            'code.size' => '验证码长度为11',
        ]);
        if ($validator->fails()) {
            return $this->sendJson($validator->getMessageBag()->toArray(),'error param','400000');
        }

        $phoneNum=$this->request['tel'];
        $code=$this->request['code'];
        $real_code=Cache::get($phoneNum);

        //验证短信验证码
        if ($code != $real_code){
            return $this->sendJson('','短信验证码错误','400000');
        }

        //销毁验证码
        Cache::put($phoneNum,'');

        /**
         * 没有经纪人，登录部分代码待开发
         */
    }


}
